package com.kkb.controller;

import com.github.pagehelper.PageInfo;
import com.kkb.pojo.Role;
import com.kkb.pojo.User;
import com.kkb.service.UserService;
import com.kkb.vo.ResultVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("user")
@ResponseBody
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ResultVO<User> selectUserInPage(Integer index,Integer size, String username){
        PageInfo<User> userPageInfo = userService.selectUserInPage(index, size, username);
        if (userPageInfo!=null){
            return new ResultVO<User>(userPageInfo);
        }
        return new ResultVO<>(404,"暂无数据");
    }

    @RequestMapping(value = "{id}",method = RequestMethod.DELETE)
    public ResultVO<User> deleteUser(@PathVariable("id") Integer id){
        int i = userService.deleteUserById(id);
        if (i>0){
            return new ResultVO<>();
        }
        return new ResultVO<User>(500,"删除失败，服务器异常");
    }

    @RequestMapping(value = "list",method = RequestMethod.DELETE)
    public ResultVO<User> deleteUserList(@RequestParam("check") List<Integer> check){
        int i = userService.deleteUserList(check);
        if (i>0){
            return new ResultVO<User>();
        }
        return new ResultVO<>(500,"删除失败！");
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResultVO<User> insertUser(User user,
                                     @RequestParam(value = "role", required = false) Role role,
                                     @RequestParam(value = "roleId") String roleId){
        int i = userService.insertUser(user, Integer.parseInt(roleId));
        if (i>0){
            return new ResultVO<>();
        }
        return new ResultVO<>(500,"新增失败");
    }

    @RequestMapping(value = "{id}",method = RequestMethod.GET)
    public ResultVO<User> selectUserById(@PathVariable("id") Integer id ){
        User user = userService.selectUserById(id);
        if (user!=null){
            return new ResultVO<User>(user);
        }
        return new ResultVO<>(404,"暂无此用户信息");
    }

    @RequestMapping(value = "", method = RequestMethod.PUT)
    public ResultVO<User> updateUser(User user,
                                     @RequestParam(value = "role",required = false) Role role,
                                     @RequestParam("roleId") Integer id){
        int i = userService.updateUser(user, id);
        if (i>0){
            return new ResultVO<>();
        }
        return new ResultVO<>(500,"新增失败");
    }
}
